import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

// 主系统类
class CinemaSystem {
    private DataManager dataManager;
    private Scanner scanner;
    private User currentUser;

    public CinemaSystem() {
        dataManager = new DataManager();
        scanner = new Scanner(System.in);
    }

    public void run() {
        System.out.println("=====================================");
        System.out.println("      欢迎使用万东电影院管理系统      ");
        System.out.println("=====================================");

        while (true) {
            showMainMenu();
            int choice = getIntInput("请选择操作: ");

            switch (choice) {
                case 1:
                    login();
                    break;
                case 2:
                    System.out.println("感谢使用万东电影院管理系统，再见！");
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    private void showMainMenu() {
        System.out.println("\n---------- 主菜单 ----------");
        System.out.println("1. 登录系统");
        System.out.println("2. 退出系统");
        System.out.println("---------------------------");
    }

    private void login() {
        System.out.print("请输入用户名: ");
        String username = scanner.nextLine();
        System.out.print("请输入密码: ");
        String password = scanner.nextLine();

        User user = dataManager.getUser(username);
        if (user != null && user.getPassword().equals(password)) {
            currentUser = user;
            System.out.println("登录成功！欢迎 " + username + "！");

            // 检查是否需要修改密码
            if (user.isNeedChangePassword()) {
                changePasswordFirstLogin();
            }

            switch (user.getRole()) {
                case UserRole.ADMIN:
                    showAdminMenu();
                    break;
                case UserRole.MANAGER:
                    showManagerMenu();
                    break;
                case UserRole.FRONT_DESK:
                    showFrontDeskMenu();
                    break;
            }
        } else {
            System.out.println("用户名或密码错误！");
        }
    }

    private void changePasswordFirstLogin() {
        System.out.println("\n*** 检测到您是首次登录，需要修改默认密码 ***");
        while (true) {
            System.out.print("请输入新密码: ");
            String newPassword = scanner.nextLine();
            System.out.print("请再次输入新密码: ");
            String confirmNewPassword = scanner.nextLine();

            if (!newPassword.equals(confirmNewPassword)) {
                System.out.println("两次输入的密码不一致，请重新输入！");
                continue;
            }

            if (newPassword.length() < 6) {
                System.out.println("密码长度不能少于6位，请重新输入！");
                continue;
            }

            currentUser.setPassword(newPassword);
            dataManager.addLog(new LogEntry("修改密码", currentUser.getUsername(),
                    "首次登录修改密码"));
            System.out.println("密码修改成功！");
            break;
        }
    }

    // 管理员菜单
    private void showAdminMenu() {
        while (true) {
            System.out.println("\n========== 管理员菜单 ==========");
            System.out.println("1. 密码管理");
            System.out.println("2. 用户管理");
            System.out.println("3. 退出登录");
            System.out.println("==============================");

            int choice = getIntInput("请选择操作: ");

            switch (choice) {
                case 1:
                    showAdminPasswordMenu();
                    break;
                case 2:
                    showUserManagementMenu();
                    break;
                case 3:
                    currentUser = null;
                    System.out.println("已退出登录！");
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    private void showAdminPasswordMenu() {
        while (true) {
            System.out.println("\n---------- 密码管理 ----------");
            System.out.println("1. 修改自身密码");
            System.out.println("2. 重置用户密码");
            System.out.println("3. 返回上一级");
            System.out.println("---------------------------");

            int choice = getIntInput("请选择操作: ");

            switch (choice) {
                case 1:
                    changeOwnPassword();
                    break;
                case 2:
                    resetUserPassword();
                    break;
                case 3:
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    private void changeOwnPassword() {
        System.out.print("请输入当前密码: ");
        String currentPassword = scanner.nextLine();

        if (!currentUser.getPassword().equals(currentPassword)) {
            System.out.println("当前密码错误！");
            return;
        }

        System.out.print("请输入新密码: ");
        String newPassword = scanner.nextLine();
        System.out.print("请再次输入新密码: ");
        String confirmNewPassword = scanner.nextLine();

        if (!newPassword.equals(confirmNewPassword)) {
            System.out.println("两次输入的密码不一致！");
            return;
        }

        if (newPassword.length() < 6) {
            System.out.println("密码长度不能少于6位！");
            return;
        }

        currentUser.setPassword(newPassword);
        dataManager.addLog(new LogEntry("修改密码", currentUser.getUsername(),
                "管理员修改自身密码"));
        System.out.println("密码修改成功！");
    }

    private void resetUserPassword() {
        System.out.print("请输入要重置密码的用户名: ");
        String username = scanner.nextLine();

        User user = dataManager.getUser(username);
        if (user == null) {
            System.out.println("用户不存在！");
            return;
        }

        if ("admin".equals(username)) {
            System.out.println("不能重置管理员账户密码！");
            return;
        }

        user.setPassword("123456");
        user.setNeedChangePassword(true);
        dataManager.addLog(new LogEntry("重置密码", currentUser.getUsername(),
                "重置用户 " + username + " 的密码"));
        System.out.println("用户 " + username + " 的密码已重置为 123456，用户下次登录时需要修改密码");
    }

    private void showUserManagementMenu() {
        while (true) {
            System.out.println("\n---------- 用户管理 ----------");
            System.out.println("1. 列出所有用户");
            System.out.println("2. 添加用户");
            System.out.println("3. 查询用户");
            System.out.println("4. 修改用户");
            System.out.println("5. 删除用户");
            System.out.println("6. 返回上一级");
            System.out.println("---------------------------");

            int choice = getIntInput("请选择操作: ");

            switch (choice) {
                case 1:
                    listAllUsers();
                    break;
                case 2:
                    addUser();
                    break;
                case 3:
                    searchUser();
                    break;
                case 4:
                    modifyUser();
                    break;
                case 5:
                    deleteUser();
                    break;
                case 6:
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    private void listAllUsers() {
        System.out.println("\n---------- 用户列表 ----------");
        System.out.printf("%-10s %-15s %-15s %-15s%n", "用户ID", "用户名", "角色", "手机号");
        System.out.println("----------------------------------------");

        for (User user : dataManager.getUsers().values()) {
            System.out.printf("%-10s %-15s %-15s %-15s%n",
                    user.getUserId(), user.getUsername(), user.getRole(), user.getPhone());
        }
    }

    private void addUser() {
        System.out.print("请输入用户ID: ");
        String userId = scanner.nextLine();
        System.out.print("请输入用户名: ");
        String username = scanner.nextLine();

        if (dataManager.getUser(username) != null) {
            System.out.println("用户名已存在！");
            return;
        }

        System.out.print("请输入手机号: ");
        String phone = scanner.nextLine();
        System.out.println("请选择用户角色:");
        System.out.println("1. 经理");
        System.out.println("2. 前台");
        int roleChoice = getIntInput("请选择: ");

        UserRole role = null;
        switch (roleChoice) {
            case 1:
                role = UserRole.MANAGER;
                break;
            case 2:
                role = UserRole.FRONT_DESK;
                break;
            default:
                System.out.println("无效选择！");
                return;
        }

        User newUser = new User(userId, username, "123456", phone, role);
        dataManager.addUser(newUser);
        dataManager.addLog(new LogEntry("添加用户", currentUser.getUsername(),
                "添加用户 " + username));
        System.out.println("用户添加成功！默认密码为 123456，用户首次登录时需要修改密码");
    }

    private void searchUser() {
        System.out.println("请选择查询方式:");
        System.out.println("1. 按用户ID查询");
        System.out.println("2. 按用户名查询");
        int choice = getIntInput("请选择: ");

        User user = null;
        switch (choice) {
            case 1:
                System.out.print("请输入用户ID: ");
                String userId = scanner.nextLine();
                user = dataManager.getUsers().values().stream()
                        .filter(u -> u.getUserId().equals(userId))
                        .findFirst().orElse(null);
                break;
            case 2:
                System.out.print("请输入用户名: ");
                String username = scanner.nextLine();
                user = dataManager.getUser(username);
                break;
            default:
                System.out.println("无效选择！");
                return;
        }

        if (user != null) {
            System.out.println("\n---------- 用户信息 ----------");
            System.out.println("用户ID: " + user.getUserId());
            System.out.println("用户名: " + user.getUsername());
            System.out.println("角色: " + user.getRole());
            System.out.println("手机号: " + user.getPhone());
        } else {
            System.out.println("未找到用户！");
        }
    }

    private void modifyUser() {
        System.out.print("请输入要修改的用户名: ");
        String username = scanner.nextLine();

        if ("admin".equals(username)) {
            System.out.println("不能修改管理员账户！");
            return;
        }

        User user = dataManager.getUser(username);
        if (user == null) {
            System.out.println("用户不存在！");
            return;
        }

        System.out.println("当前用户信息:");
        System.out.println("用户ID: " + user.getUserId());
        System.out.println("用户名: " + user.getUsername());
        System.out.println("角色: " + user.getRole());
        System.out.println("手机号: " + user.getPhone());

        System.out.println("\n请选择要修改的信息:");
        System.out.println("1. 修改角色");
        System.out.println("2. 修改手机号");
        int choice = getIntInput("请选择: ");

        switch (choice) {
            case 1:
                System.out.println("请选择新角色:");
                System.out.println("1. 经理");
                System.out.println("2. 前台");
                int roleChoice = getIntInput("请选择: ");

                UserRole newRole = null;
                switch (roleChoice) {
                    case 1:
                        newRole = UserRole.MANAGER;
                        break;
                    case 2:
                        newRole = UserRole.FRONT_DESK;
                        break;
                    default:
                        System.out.println("无效选择！");
                        return;
                }

                user.setRole(newRole);
                dataManager.addLog(new LogEntry("修改用户", currentUser.getUsername(),
                        "修改用户 " + username + " 的角色为 " + newRole));
                System.out.println("角色修改成功！");
                break;
            case 2:
                System.out.print("请输入新手机号: ");
                String newPhone = scanner.nextLine();
                user.setPhone(newPhone);
                dataManager.addLog(new LogEntry("修改用户", currentUser.getUsername(),
                        "修改用户 " + username + " 的手机号"));
                System.out.println("手机号修改成功！");
                break;
            default:
                System.out.println("无效选择！");
        }
    }

    private void deleteUser() {
        System.out.print("请输入要删除的用户名: ");
        String username = scanner.nextLine();

        if ("admin".equals(username)) {
            System.out.println("不能删除管理员账户！");
            return;
        }

        User user = dataManager.getUser(username);
        if (user == null) {
            System.out.println("用户不存在！");
            return;
        }

        System.out.print("确认删除用户 " + username + " 吗？(y/n): ");
        String confirm = scanner.nextLine();

        if ("y".equalsIgnoreCase(confirm)) {
            dataManager.removeUser(username);
            dataManager.addLog(new LogEntry("删除用户", currentUser.getUsername(),
                    "删除用户 " + username));
            System.out.println("用户删除成功！");
        } else {
            System.out.println("取消删除操作！");
        }
    }

    // 经理菜单
    private void showManagerMenu() {
        while (true) {
            System.out.println("\n========== 经理菜单 ==========");
            System.out.println("1. 密码管理");
            System.out.println("2. 影片管理");
            System.out.println("3. 排片管理");
            System.out.println("4. 查看销售数据");
            System.out.println("5. 退出登录");
            System.out.println("============================");

            int choice = getIntInput("请选择操作: ");

            switch (choice) {
                case 1:
                    showManagerPasswordMenu();
                    break;
                case 2:
                    showMovieManagementMenu();
                    break;
                case 3:
                    showScheduleManagementMenu();
                    break;
                case 4:
                    showSalesData();
                    break;
                case 5:
                    currentUser = null;
                    System.out.println("已退出登录！");
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    private void showManagerPasswordMenu() {
        while (true) {
            System.out.println("\n---------- 密码管理 ----------");
            System.out.println("1. 修改自身密码");
            System.out.println("2. 重置前台用户密码");
            System.out.println("3. 返回上一级");
            System.out.println("---------------------------");

            int choice = getIntInput("请选择操作: ");

            switch (choice) {
                case 1:
                    changeOwnPassword();
                    break;
                case 2:
                    resetFrontDeskUserPassword();
                    break;
                case 3:
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    private void resetFrontDeskUserPassword() {
        System.out.print("请输入要重置密码的前台用户名: ");
        String username = scanner.nextLine();

        User user = dataManager.getUser(username);
        if (user == null) {
            System.out.println("用户不存在！");
            return;
        }

        if (user.getRole() != UserRole.FRONT_DESK) {
            System.out.println("只能重置前台用户密码！");
            return;
        }

        user.setPassword("123456");
        user.setNeedChangePassword(true);
        dataManager.addLog(new LogEntry("重置密码", currentUser.getUsername(),
                "重置前台用户 " + username + " 的密码"));
        System.out.println("前台用户 " + username + " 的密码已重置为 123456，用户下次登录时需要修改密码");
    }

    private void showMovieManagementMenu() {
        while (true) {
            System.out.println("\n---------- 影片管理 ----------");
            System.out.println("1. 列出所有影片");
            System.out.println("2. 添加影片");
            System.out.println("3. 修改影片");
            System.out.println("4. 删除影片");
            System.out.println("5. 查询影片");
            System.out.println("6. 返回上一级");
            System.out.println("---------------------------");

            int choice = getIntInput("请选择操作: ");

            switch (choice) {
                case 1:
                    listAllMovies();
                    break;
                case 2:
                    addMovie();
                    break;
                case 3:
                    modifyMovie();
                    break;
                case 4:
                    deleteMovie();
                    break;
                case 5:
                    searchMovie();
                    break;
                case 6:
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    private void listAllMovies() {
        System.out.println("\n---------- 影片列表 ----------");
        System.out.printf("%-10s %-20s %-15s %-10s %-8s %-8s%n",
                "影片ID", "片名", "导演", "类型", "时长", "评分");
        System.out.println("----------------------------------------------------------------");

        for (Movie movie : dataManager.getMovies().values()) {
            if (movie.isShowing()) {
                System.out.printf("%-10s %-20s %-15s %-10s %-8d %-8.1f%n",
                        movie.getMovieId(), movie.getTitle(), movie.getDirector(),
                        movie.getGenre(), movie.getDuration(), movie.getRating());
            }
        }
    }

    private void addMovie() {
        System.out.print("请输入影片ID: ");
        String movieId = scanner.nextLine();
        System.out.print("请输入片名: ");
        String title = scanner.nextLine();
        System.out.print("请输入导演: ");
        String director = scanner.nextLine();
        System.out.print("请输入类型: ");
        String genre = scanner.nextLine();
        int duration = getIntInput("请输入时长(分钟): ");
        double rating = getDoubleInput("请输入评分: ");

        Movie movie = new Movie(movieId, title, director, genre, duration, rating);
        dataManager.addMovie(movie);
        dataManager.addLog(new LogEntry("添加影片", currentUser.getUsername(),
                "添加影片 " + title));
        System.out.println("影片添加成功！");
    }

    private void modifyMovie() {
        System.out.print("请输入要修改的影片ID: ");
        String movieId = scanner.nextLine();

        Movie movie = dataManager.getMovie(movieId);
        if (movie == null) {
            System.out.println("影片不存在！");
            return;
        }

        System.out.println("当前影片信息:");
        System.out.println("影片ID: " + movie.getMovieId());
        System.out.println("片名: " + movie.getTitle());
        System.out.println("导演: " + movie.getDirector());
        System.out.println("类型: " + movie.getGenre());
        System.out.println("时长: " + movie.getDuration() + "分钟");
        System.out.println("评分: " + movie.getRating());

        System.out.println("\n请选择要修改的信息:");
        System.out.println("1. 片名");
        System.out.println("2. 导演");
        System.out.println("3. 类型");
        System.out.println("4. 时长");
        System.out.println("5. 评分");
        int choice = getIntInput("请选择: ");

        switch (choice) {
            case 1:
                System.out.print("请输入新片名: ");
                String newTitle = scanner.nextLine();
                movie.setTitle(newTitle);
                dataManager.addLog(new LogEntry("修改影片", currentUser.getUsername(),
                        "修改影片 " + movieId + " 的片名"));
                System.out.println("片名修改成功！");
                break;
            case 2:
                System.out.print("请输入新导演: ");
                String newDirector = scanner.nextLine();
                movie.setDirector(newDirector);
                dataManager.addLog(new LogEntry("修改影片", currentUser.getUsername(),
                        "修改影片 " + movieId + " 的导演"));
                System.out.println("导演修改成功！");
                break;
            case 3:
                System.out.print("请输入新类型: ");
                String newGenre = scanner.nextLine();
                movie.setGenre(newGenre);
                dataManager.addLog(new LogEntry("修改影片", currentUser.getUsername(),
                        "修改影片 " + movieId + " 的类型"));
                System.out.println("类型修改成功！");
                break;
            case 4:
                int newDuration = getIntInput("请输入新时长(分钟): ");
                movie.setDuration(newDuration);
                dataManager.addLog(new LogEntry("修改影片", currentUser.getUsername(),
                        "修改影片 " + movieId + " 的时长"));
                System.out.println("时长修改成功！");
                break;
            case 5:
                double newRating = getDoubleInput("请输入新评分: ");
                movie.setRating(newRating);
                dataManager.addLog(new LogEntry("修改影片", currentUser.getUsername(),
                        "修改影片 " + movieId + " 的评分"));
                System.out.println("评分修改成功！");
                break;
            default:
                System.out.println("无效选择！");
        }
    }

    private void deleteMovie() {
        System.out.print("请输入要删除的影片ID: ");
        String movieId = scanner.nextLine();

        Movie movie = dataManager.getMovie(movieId);
        if (movie == null) {
            System.out.println("影片不存在！");
            return;
        }

        // 检查是否有排片
        boolean hasSchedule = dataManager.getSessions().values().stream()
                .anyMatch(session -> session.getMovieId().equals(movieId));

        if (hasSchedule) {
            System.out.println("该影片已有排片，不允许删除！");
            return;
        }

        System.out.print("确认删除影片 " + movie.getTitle() + " 吗？(y/n): ");
        String confirm = scanner.nextLine();

        if ("y".equalsIgnoreCase(confirm)) {
            movie.setShowing(false);
            dataManager.addLog(new LogEntry("删除影片", currentUser.getUsername(),
                    "删除影片 " + movie.getTitle()));
            System.out.println("影片删除成功！");
        } else {
            System.out.println("取消删除操作！");
        }
    }

    private void searchMovie() {
        System.out.println("请输入查询条件（直接回车跳过该条件）:");
        System.out.print("片名: ");
        String title = scanner.nextLine();
        System.out.print("导演: ");
        String director = scanner.nextLine();
        System.out.print("类型: ");
        String genre = scanner.nextLine();

        System.out.println("\n---------- 查询结果 ----------");
        System.out.printf("%-10s %-20s %-15s %-10s %-8s %-8s%n",
                "影片ID", "片名", "导演", "类型", "时长", "评分");
        System.out.println("----------------------------------------------------------------");

        boolean found = false;
        for (Movie movie : dataManager.getMovies().values()) {
            if (!movie.isShowing()) continue;

            boolean match = true;
            if (!title.isEmpty() && !movie.getTitle().contains(title)) match = false;
            if (!director.isEmpty() && !movie.getDirector().contains(director)) match = false;
            if (!genre.isEmpty() && !movie.getGenre().contains(genre)) match = false;

            if (match) {
                System.out.printf("%-10s %-20s %-15s %-10s %-8d %-8.1f%n",
                        movie.getMovieId(), movie.getTitle(), movie.getDirector(),
                        movie.getGenre(), movie.getDuration(), movie.getRating());
                found = true;
            }
        }

        if (!found) {
            System.out.println("未找到符合条件的影片！");
        }
    }

    private void showScheduleManagementMenu() {
        while (true) {
            System.out.println("\n---------- 排片管理 ----------");
            System.out.println("1. 增加场次");
            System.out.println("2. 修改场次");
            System.out.println("3. 删除场次");
            System.out.println("4. 列出所有场次");
            System.out.println("5. 自动排片");
            System.out.println("6. 返回上一级");
            System.out.println("---------------------------");

            int choice = getIntInput("请选择操作: ");

            switch (choice) {
                case 1:
                    addSession();
                    break;
                case 2:
                    modifySession();
                    break;
                case 3:
                    deleteSession();
                    break;
                case 4:
                    listSessions();
                    break;
                case 5:
                    autoSchedule();
                    break;
                case 6:
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    private void addSession() {
        System.out.print("请输入场次ID: ");
        String sessionId = scanner.nextLine();

        System.out.println("请选择影片:");
        listAllMovies();
        System.out.print("请输入影片ID: ");
        String movieId = scanner.nextLine();

        if (!dataManager.getMovies().containsKey(movieId)) {
            System.out.println("影片不存在！");
            return;
        }

        System.out.println("请选择放映厅:");
        listAllHalls();
        System.out.print("请输入放映厅ID: ");
        String hallId = scanner.nextLine();

        if (!dataManager.getHalls().containsKey(hallId)) {
            System.out.println("放映厅不存在！");
            return;
        }

        System.out.print("请输入开始时间(格式: yyyy-MM-dd HH:mm): ");
        String timeStr = scanner.nextLine();
        LocalDateTime startTime;
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
            startTime = LocalDateTime.parse(timeStr, formatter);
        } catch (Exception e) {
            System.out.println("时间格式错误！");
            return;
        }

        // 检查是否可以提前一周安排
        LocalDateTime maxScheduleTime = LocalDateTime.now().plusWeeks(1);
        if (startTime.isAfter(maxScheduleTime)) {
            System.out.println("只能提前一周安排场次！");
            return;
        }

        double price = getDoubleInput("请输入票价: ");

        Session session = new Session(sessionId, movieId, hallId, startTime, price);
        dataManager.addSession(session);
        dataManager.addLog(new LogEntry("添加场次", currentUser.getUsername(),
                "添加场次 " + sessionId + " 影片:" + movieId));
        System.out.println("场次添加成功！");
    }

    private void listAllHalls() {
        System.out.printf("%-10s %-15s %-8s %-10s %-10s%n",
                "放映厅ID", "名称", "排数", "每排座位数", "总座位数");
        System.out.println("------------------------------------------------------------");

        for (Hall hall : dataManager.getHalls().values()) {
            System.out.printf("%-10s %-15s %-8d %-12d %-12d%n",
                    hall.getHallId(), hall.getName(), hall.getRows(),
                    hall.getSeatsPerRow(), hall.getTotalSeats());
        }
    }

    private void modifySession() {
        System.out.print("请输入要修改的场次ID: ");
        String sessionId = scanner.nextLine();

        Session session = dataManager.getSession(sessionId);
        if (session == null) {
            System.out.println("场次不存在！");
            return;
        }

        // 检查是否已有售票
        if (session.getBookedSeatCount() > 0) {
            System.out.println("该场次已有售票，不允许修改！");
            return;
        }

        System.out.println("当前场次信息:");
        System.out.println("场次ID: " + session.getSessionId());
        System.out.println("影片: " + dataManager.getMovie(session.getMovieId()).getTitle());
        System.out.println("放映厅: " + dataManager.getHall(session.getHallId()).getName());
        System.out.println("开始时间: " + session.getStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));
        System.out.println("票价: " + session.getPrice());

        System.out.println("\n请选择要修改的信息:");
        System.out.println("1. 影片");
        System.out.println("2. 放映厅");
        System.out.println("3. 开始时间");
        System.out.println("4. 票价");
        int choice = getIntInput("请选择: ");

        switch (choice) {
            case 1:
                listAllMovies();
                System.out.print("请输入新影片ID: ");
                String newMovieId = scanner.nextLine();
                if (!dataManager.getMovies().containsKey(newMovieId)) {
                    System.out.println("影片不存在！");
                    return;
                }
                session.setMovieId(newMovieId);
                dataManager.addLog(new LogEntry("修改场次", currentUser.getUsername(),
                        "修改场次 " + sessionId + " 的影片"));
                System.out.println("影片修改成功！");
                break;
            case 2:
                listAllHalls();
                System.out.print("请输入新放映厅ID: ");
                String newHallId = scanner.nextLine();
                if (!dataManager.getHalls().containsKey(newHallId)) {
                    System.out.println("放映厅不存在！");
                    return;
                }
                session.setHallId(newHallId);
                dataManager.addLog(new LogEntry("修改场次", currentUser.getUsername(),
                        "修改场次 " + sessionId + " 的放映厅"));
                System.out.println("放映厅修改成功！");
                break;
            case 3:
                System.out.print("请输入新开始时间(格式: yyyy-MM-dd HH:mm): ");
                String timeStr = scanner.nextLine();
                try {
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
                    LocalDateTime newStartTime = LocalDateTime.parse(timeStr, formatter);
                    session.setStartTime(newStartTime);
                    dataManager.addLog(new LogEntry("修改场次", currentUser.getUsername(),
                            "修改场次 " + sessionId + " 的开始时间"));
                    System.out.println("开始时间修改成功！");
                } catch (Exception e) {
                    System.out.println("时间格式错误！");
                }
                break;
            case 4:
                double newPrice = getDoubleInput("请输入新票价: ");
                session.setPrice(newPrice);
                dataManager.addLog(new LogEntry("修改场次", currentUser.getUsername(),
                        "修改场次 " + sessionId + " 的票价"));
                System.out.println("票价修改成功！");
                break;
            default:
                System.out.println("无效选择！");
        }
    }

    private void deleteSession() {
        System.out.print("请输入要删除的场次ID: ");
        String sessionId = scanner.nextLine();

        Session session = dataManager.getSession(sessionId);
        if (session == null) {
            System.out.println("场次不存在！");
            return;
        }

        // 检查是否已有售票
        if (session.getBookedSeatCount() > 0) {
            System.out.println("该场次已有售票，不允许删除！");
            return;
        }

        System.out.print("确认删除场次 " + sessionId + " 吗？(y/n): ");
        String confirm = scanner.nextLine();

        if ("y".equalsIgnoreCase(confirm)) {
            dataManager.removeSession(sessionId);
            dataManager.addLog(new LogEntry("删除场次", currentUser.getUsername(),
                    "删除场次 " + sessionId));
            System.out.println("场次删除成功！");
        } else {
            System.out.println("取消删除操作！");
        }
    }

    private void listSessions() {
        System.out.println("请选择时间范围:");
        System.out.println("1. 默认(最近一周)");
        System.out.println("2. 当日");
        System.out.println("3. 最近3日");
        int choice = getIntInput("请选择: ");

        LocalDateTime now = LocalDateTime.now();
        LocalDateTime start, end;

        switch (choice) {
            case 1:
                start = now;
                end = now.plusWeeks(1);
                break;
            case 2:
                start = now.with(LocalTime.MIDNIGHT);
                end = start.plusDays(1);
                break;
            case 3:
                start = now;
                end = now.plusDays(3);
                break;
            default:
                System.out.println("无效选择，使用默认范围！");
                start = now;
                end = now.plusWeeks(1);
        }

        List<Session> sessions = dataManager.getSessionsByDateRange(start, end);
        sessions.sort(Comparator.comparing(Session::getStartTime));

        System.out.println("\n---------- 场次列表 ----------");
        System.out.printf("%-12s %-15s %-15s %-20s %-10s %-10s %-10s%n",
                "场次ID", "影片", "放映厅", "开始时间", "票价", "已售", "总计");
        System.out.println("-------------------------------------------------------------------------------------");

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd HH:mm");
        for (Session session : sessions) {
            Movie movie = dataManager.getMovie(session.getMovieId());
            Hall hall = dataManager.getHall(session.getHallId());
            int totalSeats = hall.getTotalSeats();
            int bookedSeats = session.getBookedSeatCount();

            System.out.printf("%-12s %-15s %-15s %-20s %-10.2f %-10d %-10d%n",
                    session.getSessionId(),
                    movie != null ? movie.getTitle() : "未知影片",
                    hall != null ? hall.getName() : "未知影厅",
                    session.getStartTime().format(formatter),
                    session.getPrice(),
                    bookedSeats,
                    totalSeats);
        }
    }

    private void autoSchedule() {
        // 简单的自动排片算法：按评分排序，高分影片安排在黄金时间段
        List<Movie> movies = dataManager.getMovies().values().stream()
                .filter(Movie::isShowing)
                .sorted((m1, m2) -> Double.compare(m2.getRating(), m1.getRating()))
                .collect(Collectors.toList());

        // 黄金时间段定义：18:00-22:00
        LocalTime goldenStart = LocalTime.of(18, 0);
        LocalTime goldenEnd = LocalTime.of(22, 0);

        System.out.println("自动排片建议（评分高的影片优先安排在黄金时段）:");
        LocalDateTime scheduleTime = LocalDateTime.now().with(LocalTime.of(10, 0));

        for (int i = 0; i < Math.min(movies.size(), 5); i++) {
            Movie movie = movies.get(i);
            Hall hall = dataManager.getHalls().get("hall" + (i + 1));

            if (hall == null) continue;

            // 判断是否应该安排在黄金时段
            boolean isGoldenTime = i < 2; // 评分前2的影片安排在黄金时段
            LocalTime movieStart = isGoldenTime ? goldenStart :
                    scheduleTime.toLocalTime().isBefore(goldenStart) ?
                            scheduleTime.toLocalTime() : goldenEnd;

            LocalDateTime movieTime = scheduleTime.with(LocalTime.from(movieStart));

            System.out.printf("建议: %s 在 %s 放映《%s》(评分:%.1f)%n",
                    hall.getName(),
                    movieTime.format(DateTimeFormatter.ofPattern("MM-dd HH:mm")),
                    movie.getTitle(),
                    movie.getRating());

            // 更新下一个排片时间
            scheduleTime = movieTime.plusMinutes(movie.getDuration() + 5); // 加5分钟间隔
        }

        System.out.println("自动排片完成！请根据建议手动添加场次。");
    }

    private void showSalesData() {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime startOfDay = now.with(LocalTime.MIDNIGHT);
        LocalDateTime startOfWeek = startOfDay.minusDays(now.getDayOfWeek().getValue() - 1);
        LocalDateTime startOfMonth = startOfDay.withDayOfMonth(1);

        System.out.println("\n---------- 销售数据 ----------");
        System.out.println("1. 当日销售数据:");
        int todaySales = dataManager.getSoldTicketsCount(startOfDay, startOfDay.plusDays(1));
        System.out.println("   总售票数: " + todaySales);

        System.out.println("2. 本周销售数据:");
        int weekSales = dataManager.getSoldTicketsCount(startOfWeek, startOfWeek.plusWeeks(1));
        System.out.println("   总售票数: " + weekSales);

        System.out.println("3. 本月销售数据:");
        int monthSales = dataManager.getSoldTicketsCount(startOfMonth, startOfMonth.plusMonths(1));
        System.out.println("   总售票数: " + monthSales);

        // 显示今日各场次销售情况
        System.out.println("\n今日各场次销售情况:");
        LocalDateTime endOfDay = startOfDay.plusDays(1);
        List<Session> todaySessions = dataManager.getSessionsByDateRange(startOfDay, endOfDay);

        System.out.printf("%-12s %-15s %-10s %-10s%n", "场次ID", "影片", "已售", "总计");
        System.out.println("------------------------------------------------");

        for (Session session : todaySessions) {
            Movie movie = dataManager.getMovie(session.getMovieId());
            Hall hall = dataManager.getHall(session.getHallId());
            int totalSeats = hall != null ? hall.getTotalSeats() : 0;
            int bookedSeats = session.getBookedSeatCount();

            System.out.printf("%-12s %-15s %-10d %-10d%n",
                    session.getSessionId(),
                    movie != null ? movie.getTitle() : "未知影片",
                    bookedSeats,
                    totalSeats);
        }
    }

    // 前台菜单
    private void showFrontDeskMenu() {
        while (true) {
            System.out.println("\n========== 前台菜单 ==========");
            System.out.println("1. 查看正在上映影片");
            System.out.println("2. 查看场次信息");
            System.out.println("3. 查看场次座位信息");
            System.out.println("4. 售票");
            System.out.println("5. 退票");
            System.out.println("6. 退出登录");
            System.out.println("============================");

            int choice = getIntInput("请选择操作: ");

            switch (choice) {
                case 1:
                    listAllMovies();
                    break;
                case 2:
                    listSessions();
                    break;
                case 3:
                    showSessionSeats();
                    break;
                case 4:
                    sellTicket();
                    break;
                case 5:
                    refundTicket();
                    break;
                case 6:
                    currentUser = null;
                    System.out.println("已退出登录！");
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    private void showSessionSeats() {
        System.out.print("请输入场次ID: ");
        String sessionId = scanner.nextLine();

        Session session = dataManager.getSession(sessionId);
        if (session == null) {
            System.out.println("场次不存在！");
            return;
        }

        Hall hall = dataManager.getHall(session.getHallId());
        if (hall == null) {
            System.out.println("放映厅信息错误！");
            return;
        }

        Movie movie = dataManager.getMovie(session.getMovieId());
        System.out.println("\n影片: " + (movie != null ? movie.getTitle() : "未知"));
        System.out.println("放映厅: " + hall.getName());
        System.out.println("时间: " + session.getStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));
        System.out.println("票价: " + session.getPrice());
        System.out.println("总座位数: " + hall.getTotalSeats());
        System.out.println("空闲座位数: " + (hall.getTotalSeats() - session.getBookedSeatCount()));

        // 显示座位图
        System.out.println("\n座位图 (X=已售, O=空闲):");
        Map<String, Boolean> seatStatus = new HashMap<>();
        for (int row = 1; row <= hall.getRows(); row++) {
            for (int seat = 1; seat <= hall.getSeatsPerRow(); seat++) {
                String seatId = row + "-" + seat;
                seatStatus.put(seatId, session.isSeatBooked(seatId));
            }
        }

        System.out.print("   ");
        for (int seat = 1; seat <= hall.getSeatsPerRow(); seat++) {
            System.out.printf("%2d ", seat);
        }
        System.out.println();

        for (int row = 1; row <= hall.getRows(); row++) {
            System.out.printf("%2d ", row);
            for (int seat = 1; seat <= hall.getSeatsPerRow(); seat++) {
                String seatId = row + "-" + seat;
                System.out.print(seatStatus.get(seatId) ? " X " : " O ");
            }
            System.out.println();
        }
    }

    private void sellTicket() {
        System.out.print("请输入场次ID: ");
        String sessionId = scanner.nextLine();

        Session session = dataManager.getSession(sessionId);
        if (session == null) {
            System.out.println("场次不存在！");
            return;
        }

        // 检查电影是否已经开始
        if (session.getStartTime().isBefore(LocalDateTime.now())) {
            System.out.println("该场次已经开始，不能售票！");
            return;
        }

        Hall hall = dataManager.getHall(session.getHallId());
        if (hall == null) {
            System.out.println("放映厅信息错误！");
            return;
        }

        // 显示座位图并选择座位
        showSessionSeats();

        System.out.print("请选择座位(格式: 行-列，例如: 3-5): ");
        String seatId = scanner.nextLine();

        // 验证座位有效性
        String[] parts = seatId.split("-");
        if (parts.length != 2) {
            System.out.println("座位格式错误！");
            return;
        }

        try {
            int row = Integer.parseInt(parts[0]);
            int seat = Integer.parseInt(parts[1]);

            if (row < 1 || row > hall.getRows() || seat < 1 || seat > hall.getSeatsPerRow()) {
                System.out.println("座位不存在！");
                return;
            }

            if (session.isSeatBooked(seatId)) {
                System.out.println("该座位已被预订！");
                return;
            }
        } catch (NumberFormatException e) {
            System.out.println("座位格式错误！");
            return;
        }

        // 处理儿童票折扣
        double finalPrice = session.getPrice();
        System.out.print("是否为儿童票(是/否): ");
        String isChild = scanner.nextLine();
        if ("是".equalsIgnoreCase(isChild)) {
            finalPrice *= 0.5; // 儿童票5折
            System.out.println("儿童票享受5折优惠！");
        }

        // 生成票号并创建电影票
        String ticketId = "T" + System.currentTimeMillis();
        Ticket ticket = new Ticket(ticketId, sessionId, seatId, finalPrice);
        dataManager.addTicket(ticket);
        session.bookSeat(seatId, ticketId);

        // 输出电影票信息
        Movie movie = dataManager.getMovie(session.getMovieId());
        System.out.println("\n========== 电影票 ==========");
        System.out.println("票号: " + ticketId);
        System.out.println("影片: " + (movie != null ? movie.getTitle() : "未知"));
        System.out.println("放映厅: " + hall.getName());
        System.out.println("座位: " + seatId);
        System.out.println("时间: " + session.getStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));
        System.out.println("价格: " + String.format("%.2f", finalPrice) + "元");
        System.out.println("============================");
        System.out.println("购票成功！请妥善保管票号。");
    }

    private void refundTicket() {
        System.out.print("请输入票号: ");
        String ticketId = scanner.nextLine();

        Ticket ticket = dataManager.getTicket(ticketId);
        if (ticket == null) {
            System.out.println("票号不存在！");
            return;
        }

        if (ticket.isRefunded()) {
            System.out.println("该票已退！");
            return;
        }

        Session session = dataManager.getSession(ticket.getSessionId());
        if (session == null) {
            System.out.println("场次信息错误！");
            return;
        }

        // 检查是否在退票时间范围内（电影开始前1小时）
        LocalDateTime oneHourBefore = session.getStartTime().minusHours(1);
        if (LocalDateTime.now().isAfter(oneHourBefore)) {
            System.out.println("已超过退票时间（电影开始前1小时），不能退票！");
            return;
        }

        // 确认退票
        System.out.print("确认退票吗？(y/n): ");
        String confirm = scanner.nextLine();

        if ("y".equalsIgnoreCase(confirm)) {
            ticket.setRefunded(true);
            session.releaseSeat(ticket.getSeatId());
            dataManager.addLog(new LogEntry("退票", currentUser.getUsername(),
                    "退票 " + ticketId));
            System.out.println("退票成功！退款金额: " + String.format("%.2f", ticket.getPrice()) + "元");
        } else {
            System.out.println("取消退票操作！");
        }
    }

    // 工具方法
    private int getIntInput(String prompt) {
        while (true) {
            try {
                System.out.print(prompt);
                return Integer.parseInt(scanner.nextLine());
            } catch (NumberFormatException e) {
                System.out.println("请输入有效的数字！");
            }
        }
    }

    private double getDoubleInput(String prompt) {
        while (true) {
            try {
                System.out.print(prompt);
                return Double.parseDouble(scanner.nextLine());
            } catch (NumberFormatException e) {
                System.out.println("请输入有效的数字！");
            }
        }
    }
}
